/*
 * All content copyright http://www.j2eefast.com, unless
 * otherwise indicated. All rights reserved.
 * No deletion without permission
 */
package com.j2eefast.web.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.j2eefast.web.entity.JumucClassifyEntity;
import com.j2eefast.web.entity.JumucGoodsEntity;
import com.j2eefast.web.mapper.JumucGoodsMapper;
import com.j2eefast.common.core.page.Query;
import com.j2eefast.common.core.utils.PageUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.j2eefast.common.core.utils.ToolUtil;
import com.j2eefast.framework.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;

/**
 * 【请填写功能名称】Service接口
 * @author: ZhouZhou
 * @date 2021-06-15 13:35:36
 */
@Service
public class JumucGoodsService extends ServiceImpl<JumucGoodsMapper,JumucGoodsEntity> {

	@Resource
	private JumucGoodsMapper jumucGoodsMapper;
	
	@Autowired
	private JumucLoginService jumucLoginService;
	
	@Autowired
	private JumucClassifyService jumucClassifyService;

	private final static String GOODS_LIST_URL = "http://app.jumuc.com/jmGoods/selectGoodsByGoodsClass";


	private final static String FORMAT_GOODS_DETAIL_URL = "http://app.jumuc.com/jmGoods/%s";

	public void initGoodsList(){

		String token = jumucLoginService.getToken();

		List<JumucClassifyEntity> classifyDataList = jumucClassifyService.getThreeClassify();
		Map<String,Object> paramsMap = new HashMap<>();
		for(JumucClassifyEntity classify : classifyDataList){

			paramsMap.put("currentPage",1);
			paramsMap.put("goodsClassId",classify.getId());

			JSONObject data = doRequest(token,paramsMap);
			Integer pageNum = data.getJSONObject("data").getInt("pages");
			if(pageNum > 0) {
				doSaveData(data.getJSONObject("data"), token);

				if (pageNum >= 2) {
					for (int i = 2; i <= pageNum; i++) {
						paramsMap.put("currentPage", i);
						data = doRequest(token, paramsMap);
						doSaveData(data.getJSONObject("data"), token);
					}
				}
			}
		}


	}

	private void doSaveData(JSONObject data,String token) {

		JSONArray dataArr = data.getJSONArray("list");
		if(dataArr == null && dataArr.size() == 0) return;

		for(int i = 0 ; i < dataArr.size();i++){
			JSONObject d = dataArr.getJSONObject(i);

			JumucGoodsEntity entity = parseData(d,token);

			JumucGoodsEntity query = new JumucGoodsEntity();
			query.setId(entity.getId());

			List<JumucGoodsEntity> dataList = jumucGoodsMapper.findList(query);
			if(dataList != null && dataList.size() > 0){
				entity.setPkId(dataList.get(0).getPkId());
			}

			this.saveOrUpdate(entity);
		}

	}

	private JumucGoodsEntity parseData(JSONObject data,String token) {
		Long id = data.getLong("id");

		String url = String.format(FORMAT_GOODS_DETAIL_URL,id);

		String result = HttpRequest.get(url).header("Content-Type","application/json;charset=UTF-8")
				.header("Authorization",token)
				.execute().body();

		JSONObject json = JSONUtil.parseObj(result);

		JumucGoodsEntity goods = parseData(json);

		return goods;
	}

	private JumucGoodsEntity parseData(JSONObject jsonData) {
		JSONObject json = jsonData.getJSONObject("data");
		if(json == null) return null;

		JSONObject goods = json.getJSONObject("goods");
		if(goods == null) return null;

		JumucGoodsEntity e = new JumucGoodsEntity();
		e.setCreatetime(goods.getStr("createtime"));
		e.setId(goods.getLong("id"));
		e.setFactoryPrice(goods.getBigDecimal("factoryPrice"));
		e.setGcId(goods.getLong("gcId"));
		e.setGoodsBrandId(goods.getLong("goodsBrandId"));
		e.setGoodsCurrentPrice(goods.getBigDecimal("goodsCurrentPrice"));
		e.setGoodsInventory(goods.getBigDecimal("goodsInventory"));
		e.setGoodsName(goods.getStr("goodsName"));
		e.setGoodsPrice(goods.getBigDecimal("goodsPrice"));
		e.setGoodsUnitSeller(goods.getStr("goodsUnitSeller"));
		e.setShowMarketPrice(goods.getBigDecimal("showMarketPrice"));
		e.setShowPrice(goods.getBigDecimal("showPrice"));
		e.setSpec(goods.getStr("spec"));
		e.setSpecificationDescription(goods.getStr("specificationDescription"));

		return e;
	}

	private JSONObject doRequest(String token,Map<String,Object> paramMap){
		String res = HttpRequest.post(GOODS_LIST_URL).header("Content-Type","application/json;charset=UTF-8")
				.header("Authorization",token)
				.body(JSONUtil.toJsonStr(paramMap))
				.execute().body();

		JSONObject data = JSONUtil.parseObj(res);

		return data;
	}

	/**
	 * mybaitis-plus 单表页面分页查询
     */
	public PageUtil findPage(Map<String, Object> params) {
		QueryWrapper<JumucGoodsEntity> queryWrapper = new QueryWrapper<JumucGoodsEntity>();
		String createtime = (String) params.get("createtime");
        queryWrapper.eq(ToolUtil.isNotEmpty(createtime), "createtime", createtime);
		String factoryPrice = (String) params.get("factoryPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(factoryPrice), "factory_price", factoryPrice);
		String gcId = (String) params.get("gcId");
        queryWrapper.eq(ToolUtil.isNotEmpty(gcId), "gc_id", gcId);
		String goodsBrandId = (String) params.get("goodsBrandId");
        queryWrapper.eq(ToolUtil.isNotEmpty(goodsBrandId), "goods_brand_id", goodsBrandId);
		String goodsCurrentPrice = (String) params.get("goodsCurrentPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(goodsCurrentPrice), "goods_current_price", goodsCurrentPrice);
		String goodsInventory = (String) params.get("goodsInventory");
        queryWrapper.eq(ToolUtil.isNotEmpty(goodsInventory), "goods_inventory", goodsInventory);
		String goodsName = (String) params.get("goodsName");
        queryWrapper.like(ToolUtil.isNotEmpty(goodsName), "goods_name", goodsName);
		String goodsPrice = (String) params.get("goodsPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(goodsPrice), "goods_price", goodsPrice);
		String goodsUnitSeller = (String) params.get("goodsUnitSeller");
        queryWrapper.eq(ToolUtil.isNotEmpty(goodsUnitSeller), "goods_unit_seller", goodsUnitSeller);
		String showMarketPrice = (String) params.get("showMarketPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(showMarketPrice), "show_market_price", showMarketPrice);
		String showPrice = (String) params.get("showPrice");
        queryWrapper.eq(ToolUtil.isNotEmpty(showPrice), "show_price", showPrice);
		String spec = (String) params.get("spec");
        queryWrapper.eq(ToolUtil.isNotEmpty(spec), "spec", spec);
		String specificationDescription = (String) params.get("specificationDescription");
        queryWrapper.eq(ToolUtil.isNotEmpty(specificationDescription), "specification_description", specificationDescription);
		Page<JumucGoodsEntity> page = jumucGoodsMapper.selectPage(new Query<JumucGoodsEntity>(params).getPage(), queryWrapper);
		return new PageUtil(page);
    }

	/**
	 * 自定义分页查询，含关联实体对像
	 */
	public PageUtil findPage(Map<String, Object> params,JumucGoodsEntity jumucGoodsEntity) {
		Page<JumucGoodsEntity> page = jumucGoodsMapper.findPage(new Query<JumucGoodsEntity>(params).getPage(),
					jumucGoodsEntity,
				(String) params.get(Constant.SQL_FILTER));
		return new PageUtil(page);
	}

	/**
	* 查列表
	*/
	public List<JumucGoodsEntity> findList(JumucGoodsEntity jumucGoodsEntity){
		return jumucGoodsMapper.findList(jumucGoodsEntity);
	}

	/**
     * 批量删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteBatchByIds(Long[] ids) {
		return this.removeByIds(Arrays.asList(ids));
	}

	/**
     * 单个删除
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean delJumucGoodsById(Long pkId) {
		return this.removeById(pkId);
	}

	/**
     * 保存
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean addJumucGoods(JumucGoodsEntity jumucGoods){
		if(this.save(jumucGoods)){
			return true;
		}
        return false;
    }

	/**
     * 修改根居ID
     */
	@Transactional(rollbackFor = Exception.class)
	public boolean updateJumucGoodsById(JumucGoodsEntity jumucGoods) {
		if(this.updateById(jumucGoods)){
			return true;
		}
		return false;
	}

	/**
     * 根居ID获取对象
     */
	public JumucGoodsEntity findJumucGoodsById(Long pkId){
		return jumucGoodsMapper.findJumucGoodsById(pkId);
	}


}
